# 豆瓣图书TOP250爬取
from bs4 import BeautifulSoup
from lxml import etree
from pyquery import PyQuery
from requests.exceptions import RequestException
import requests
import time, json

m = 1  # 定义序号


def getPage(url):
    '''爬取指定url地址的信息'''
    try:
        # 定义请求头信息
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) Ap'
                          'pleWebKit/537.36 (KHTML, like Gecko) Chrome'
                          '/64.0.3282.119 Safari/537.36'
        }
        # 执行爬取
        res = requests.get(url, headers=headers)
        # 判断并返回结果
        if res.status_code == 200:
            return res.text
        else:
            return None
    except RequestException:
        return None


def parsePage(content, s):
    '''解析爬取网页中内容，并返回结果'''
    if s == '1':
        # ========使用BeautifulSoup解析======================
        # 初始化，返回BeautifulSoup对象
        soup = BeautifulSoup(content, 'lxml')
        # 解析网页中<table width="100%">....</table>信息（一本本书信息）
        items = soup.find_all(name="table", attrs={"width": "100%"})
        # 遍历并解析每部电影具体信息
        for item in items:
            yield {
                'index': '',
                'title': item.find(name="div", attrs={'class': 'pl2'}).find(
                        'a').attrs['title'],
                'image':
                    item.find(name="a", attrs={'class': 'nbg'}).find(
                            'img').attrs[
                        'src'],
                'actor': item.find('p', class_='pl').string.split('/')[
                    0].strip(),
                'score': item.select("div.star span.rating_nums")[0].string,
            }
    elif s == '2':
        # ========使用Xpath解析======================
        # 初始化，返回根节点对象
        html = etree.HTML(content)
        # 解析网页中<table width="100%">....</table>信息（一本本书信息）
        items = html.xpath("//table[@width='100%']")
        # 遍历并解析每部电影具体信息
        for item in items:
            yield {
                'index': '',
                'title': item.xpath(".//div[@class='pl2']/a/@title")[0],
                'image': item.xpath(".//a[@class='nbg']/img/@src")[0],
                'actor': item.xpath(".//p[@class='pl']/text()")[0].split('/')[
                    0].strip(),
                'score': item.xpath(
                        ".//span[@class='rating_nums']/text()")[0],
            }
    elif s == '3':
        # ========使用pyquery解析======================
        # 初始化，返回Pyquery对象
        doc = PyQuery(content)
        # 解析网页中<table width="100%">....</table>信息（一本本书信息）
        items = doc("table[width='100%']")
        # 遍历并解析每部电影具体信息
        for item in items.items():
            yield {
                'index': '',
                'title': item.find("div.pl2 a").attr('title'),
                'image': item.find("a.nbg img").attr('src'),
                'actor': item.find("p.pl").text().split('/')[0].strip(),
                'score': item.find("span.rating_nums").text(),
            }


def writeFile(content):
    '''解析爬取网页中内容，并返回结果'''
    with open("./result.txt", 'a', encoding="utf-8") as f:
        f.write(json.dumps(content, ensure_ascii=False) + "\n")


def main(offset, s):
    '''主程序函数，负责调度执行爬取处理'''
    global m
    url = 'https://book.douban.com/top250?start=' + str(offset)
    html = getPage(url)  # 执行爬取
    if html:
        for item in parsePage(html, s):  # 执行解析并遍历
            item['index'] = str(m)
            print(item)
            writeFile(item)
            m += 1


# 判断当前执行是否为主程序，并遍历调度主函数来爬取信息
if __name__ == '__main__':
    # main(0)
    s = input('BeautifulSoup请按1，xpath请按2，pyquery请按3:\n')
    for i in range(10):
        main(offset=i * 25, s=s)
        time.sleep(1)
